package openbang.account.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOUserException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import openbang.account.service.entity.DiaoChaItem;
import openbang.account.service.entity.DiaoChaProject;
import openbang.account.service.entity.DiaoChaRecord;
import openbang.account.service.intf.DiaoChaService;
import openbang.account.service.util.CacheHelper;
import openbang.account.service.util.PMF;
import openbang.account.service.vo.CacheKeyDefine;
import openbang.account.service.vo.DiaoChaItemRate;

/**
 * 调查服务
 * 1.显示调查
 * 2.提交调查
 * 
 * 2010-03-30 发现页面显示调查项比较慢。解决：把调查项放入 cache中
 * 
 * @author aibozeng
 *
 */

@SuppressWarnings("serial")
public class DiaoChaServiceImpl  extends RemoteServiceServlet implements DiaoChaService {
	private static final Logger log = Logger.getLogger(DiaoChaServiceImpl.class.getName());
	private static final String ProjectCode = "dc20100313";
	@Override
	public List<DiaoChaItemRate> addDiaoChaRecord(Long projectId, Long selectItemId) {
		log.warning("come in addDiaoChaRecord() projectId="+projectId+",selectItemId="+selectItemId);
		List<DiaoChaItemRate> rates = new ArrayList<DiaoChaItemRate>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		DiaoChaProject project = (DiaoChaProject)pm.getObjectById(DiaoChaProject.class,projectId);
		if(project==null){
			pm.close();
			return rates;
		}
		DiaoChaItem item = (DiaoChaItem)pm.getObjectById(DiaoChaItem.class,selectItemId);
		project.setUpdTime(new Date());
		item.setCountNum(item.getCountNum()+1);
		DiaoChaRecord record = new DiaoChaRecord();
		record.setFromIp(getThreadLocalRequest().getRemoteAddr());
		record.setItemCode(item.getCode());
		record.setProjectCode(project.getCode());
		pm.makePersistent(record);
        //pm.makePersistent(pm);
        //pm.makePersistent(item);
        pm.close();
        
        pm = PMF.get().getPersistenceManager();
        //取调查结果
        Collection<DiaoChaItem> items = null;
		Query q = pm.newQuery(DiaoChaItem.class);
		q.setFilter("projectCode == project_code");			
		q.setOrdering("viewOrder");		
		q.declareParameters("java.lang.String project_code");
		items = (Collection<DiaoChaItem>) q.execute(project.getCode());
		//统计总数
		long totalCount = 0;
		for(DiaoChaItem oneItem : items){
			totalCount = totalCount + oneItem.getCountNum();
		}
		//计算每一项的百分比。比值，如：45.3% ，返回界面是 45.3 字符串
		DecimalFormat df = new DecimalFormat("##.0");
		for(DiaoChaItem oneItem : items){
			String rate = "0"; 
			if(oneItem.getCountNum()>0){
				rate = df.format((oneItem.getCountNum()*1.0/totalCount)*100);
			}
			rates.add(new DiaoChaItemRate(oneItem.getCode(), rate));
		}		
		pm.close();
		log.warning(" rates.size="+rates.size());
		return rates;
	}

	@Override
	public DiaoChaProject getProject(String code) {
		if(code==null || code.length()<=4){
			code = ProjectCode;
		}
		log.warning("come in getProject() code="+code);
		//(1)先从缓存里找
		DiaoChaProject project = null;
		project = (DiaoChaProject)CacheHelper.get(CacheKeyDefine.DIAOCHA_PREFIX+code);		
		if(project!=null){
			//找到，返回
			log.warning("get from cache item size="+project.getItems().size());
			return project;
		}
		//(2)没有找到,再从数据库找
		PersistenceManager pm = PMF.get().getPersistenceManager();
		//project = (DiaoChaProject)pm.getObjectById(DiaoChaProject.class,id);
		Collection<DiaoChaProject> projects = null;
		Query qPrj = pm.newQuery(DiaoChaProject.class);
		qPrj.setFilter("code == project_code");			
		qPrj.declareParameters("java.lang.String project_code");
		try{
			projects = (Collection<DiaoChaProject>)qPrj.execute(code);
		}catch(JDOUserException jdou){
			pm.close();
			return null;
		}
		Collection<DiaoChaItem> items = null;		
		if(projects!=null && projects.size()>0){
			project = projects.iterator().next();
			//找到,继续取子项
			Query q = pm.newQuery(DiaoChaItem.class);
			q.setFilter("projectCode == project_code");			
			q.setOrdering("viewOrder");		
			q.declareParameters("java.lang.String project_code");
			items = (Collection<DiaoChaItem>) q.execute(project.getCode());			
		}
		else{
			//数据库也没有，创建
			//初始化 调查项目
			project = new DiaoChaProject();
			project.setCode(ProjectCode);
			project.setEndDate(new Date(System.currentTimeMillis()+1000*60*60*24*365));
			project.setDescription("您是否理解和支持开源邦的模式");
			project.setEmail("aibozeng@gmail.com");
			project.setTitle("您认可开源邦的模式吗?");			
			pm.makePersistent(project);
			//初始化调查子项
			items = new HashSet<DiaoChaItem>();
			items.add(new DiaoChaItem(ProjectCode+"-01",ProjectCode,0,"不清楚","不清楚"));
			items.add(new DiaoChaItem(ProjectCode+"-02",ProjectCode,1,"不认可","不认可"));
			items.add(new DiaoChaItem(ProjectCode+"-03",ProjectCode,2,"认可","认可"));
			items.add(new DiaoChaItem(ProjectCode+"-04",ProjectCode,3,"非常认可","非常认可"));
			pm.makePersistentAll(items);
			pm.flush();
			//断开数据库
			items = pm.detachCopyAll(items);
			project = pm.detachCopy(project);
			pm.close();
		}
		for(DiaoChaItem item : items){
			project.addItem(item);
		}
		//关闭数据库
		if(!pm.isClosed()) pm.close();
		//放入缓存中
		log.warning("prject item size="+project.getItems().size());
		log.warning("put into cache.");
		CacheHelper.put(CacheKeyDefine.DIAOCHA_PREFIX+code,project);
		return project;
	}
	
}
